package com.autonavi.yunda.yunji.core.service.thirdpartyservice;

import com.autonavi.yunda.yunji.common.exception.AmapException;
import com.autonavi.yunda.yunji.common.exception.AmapExceptionCode;
import com.autonavi.yunda.yunji.common.exception.AmapPreconditions;
import com.autonavi.yunda.yunji.common.utils.JsonUtils;
import com.autonavi.yunda.yunji.common.utils.http.HttpClient;
import com.autonavi.yunda.yunji.common.utils.http.vo.HttpResponse;
import com.autonavi.yunda.yunji.core.enums.ComponentType;
import com.autonavi.yunda.yunji.core.model.vo.ComponentData;
import com.autonavi.yunda.yunji.core.service.thirdpartyservice.vo.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.autonavi.yunda.yunji.common.exception.AmapExceptionCode.COMMON_HTTP_ERROR;

/**
 * @author cizhong.wcs
 * @date 2023/1/5 20:44
 */
@Component
@Slf4j
public class YuncangService {

    private static final String DICT_TAG_LIST_URI = "/dict/tag/list";
    private static final String UNIT_INBOUND_URI = "/unit/inbound";
    private static final String PART_INBOUND_URI = "/part/inbound";
    private static final String UNIT_UPDATE_URI = "/unit/update";
    private static final String PART_UPDATE_URI = "/part/update";
    private static final String UNIT_LIST = "/unit/list";
    private static final String PART_LIST = "/part/list";

    @Value("${yuncang.host}")
    private String yuncangHost;

    static HttpClient httpClient = new HttpClient();

    public Long syncToYuncang(ComponentType type, BasePartUnitVO baseParamVO) {
        if (baseParamVO.getId() != null) {
            return update(type, baseParamVO);
        } else {
            return inbound(type, baseParamVO);
        }
    }

    private Long inbound(ComponentType type, BasePartUnitVO baseParamVO) {
        String uri = ComponentType.unit.equals(type) ? UNIT_INBOUND_URI : PART_INBOUND_URI;
        HttpResponse httpResponse = httpClient.post(
                yuncangHost + uri,
                JsonUtils.toString(baseParamVO),
                null,
                null
        );
        YuncangUnitInboundResponse response = JsonUtils.from(httpResponse.getBody(), YuncangUnitInboundResponse.class);
        if (!response.isSuccess()) {
            throw new AmapException(AmapExceptionCode.COMMON_ILLEGAL_PARAM, "接口推送云仓新增失败:" + response.msg);
        }
        return response.data;
    }

    private Long update(ComponentType type, BasePartUnitVO baseParamVO) {
        String uri = ComponentType.unit.equals(type) ? UNIT_UPDATE_URI : PART_UPDATE_URI;
        HttpResponse httpResponse = httpClient.post(
                yuncangHost + uri,
                JsonUtils.toString(baseParamVO),
                null,
                null
        );
        YuncangPartUnitResponse response = JsonUtils.from(httpResponse.getBody(), YuncangPartUnitResponse.class);
        if (!response.isSuccess()) {
            throw new AmapException(AmapExceptionCode.COMMON_ILLEGAL_PARAM, "接口推送云仓更新失败:" + response.msg);
        }
        return baseParamVO.getId();
    }

    public List<ComponentData> fetchComponentData(List<Long> componentIds,
                                                  ComponentType componentType,
                                                  Long bdId,
                                                  String workNo) {
        if (CollectionUtils.isEmpty(componentIds)) {
            return new ArrayList<>();
        }
        String url;
        if (componentType.equals(ComponentType.unit)) {
            url = yuncangHost + UNIT_LIST + "?pageSize=100&pageNo=1" +
                    "&workNo=" + workNo +
                    "&workBdId=" + bdId +
                    "&unitIds=" + componentIds.stream().map(Object::toString).collect(Collectors.joining(","));
        } else {
            url = yuncangHost + PART_LIST + "?pageSize=100&pageNo=1" +
                    "&workNo=" + workNo +
                    "&workBdId=" + bdId +
                    "&partIds=" + componentIds.stream().map(Object::toString).collect(Collectors.joining(","));
        }
        HttpResponse httpResponse = httpClient.get(url, null);
        JsonNode response = JsonUtils.from(httpResponse.getBody(), JsonNode.class);
        AmapPreconditions.checkArgumentForUser(
                response.get("code").asInt() == 0,
                "查询零部件部件失败 componentIds = " + JsonUtils.toString(componentIds) + ",componentType=" + componentType
        );
        return JsonUtils.from(JsonUtils.toString(response.get("data").get("list")), new TypeReference<>() {
        });
    }

    public List<TagVO> listOfAllTags() {
        HttpResponse httpResponse = httpClient.get(
                yuncangHost + DICT_TAG_LIST_URI,
                null
        );
        BaseHttpResponse<List<TagVO>> response = JsonUtils.from(httpResponse.getBody(), new TypeReference<>() {
        });
        List<TagVO> result = response.getData(new TypeReference<>() {
        });
        AmapPreconditions.checkArgument(CollectionUtils.isNotEmpty(result), COMMON_HTTP_ERROR, "获取云仓标签集合接口失败");
        return result;
    }


}
